package cn.huiyunche.base.service.framework.utils;

import cn.huiyunche.base.service.constant.App;
import cn.huiyunche.base.service.framework.redis.MindsJedisConnectionFactory;
import cn.huiyunche.base.service.vo.UserVo;
import cn.huiyunche.tools.basic.Encodes;
import cn.huiyunche.tools.basic.PropertiesLoader;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

/**
 * 知车客运段端工具类
 *
 * @author hdy [Tuffy]
 */
@Component
public class HYCUtils {

    /**
     * 系统配置文件名
     */
    private static final String CONSTANT_PROPER = "constant.properties";
    /**
     * 微信企业号token缓存key
     */
    private static final String WEIXIN_QY_ACCESS_TOKEN_CACHE = "weixin_qy_access_token_cache";
    /**
     * 微信token缓存key
     */
    private static final String WEIXIN_ACCESS_TOKEN_CACHE = "weixin_access_token_cache";
    /**
     * 微信user code 后缀缓存key
     */
    private static final String WEIXIN_USER_CODE_SUFFIX_CACHE = "weixin_user_code_suffix";
    /**
     * 微信当前菜单后缀缓存key
     */
    private static final String WEIXIN_THISMENU_SUFFIX_CACHE = "weixin_thismenu_suffix";
    /**
     * 用户抽奖后缀缓存key
     */
    private static final String DRAW_USER_SUFFIX_CACHE = "draw_user_suffix";

    private static final int DRAW_USER_TIMER = 60 * 10;

    /**
     * constant资源文件对象
     */
    private static PropertiesLoader constantPropertiesLoader = null;

    /**
     * 缓存对象
     */
    private static MindsJedisConnectionFactory connectionFactory = null;

    /**
     * 注入缓存
     *
     * @param mindsJedisConnectionFactory 缓存工厂
     */
    @Autowired
    public void setConnectionFactory(MindsJedisConnectionFactory mindsJedisConnectionFactory) {
        connectionFactory = mindsJedisConnectionFactory;
    }

    // @Autowired

    /**
     * 获取constant资源文件
     *
     * @return constant资源文件配置对象
     */
    public static PropertiesLoader getConstantPropertiesLoader() {
        if (null == constantPropertiesLoader) {
            constantPropertiesLoader = new PropertiesLoader(CONSTANT_PROPER);
        }
        return constantPropertiesLoader;
    }

    /**
     * 设置缓存
     *
     * @param key
     * @return
     */
    public static String getJedisCache(String key) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            return jedis.get(key);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取缓存
     *
     * @param key
     * @param value
     */
    public static void setJedisCache(String key, int timer, String value) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            jedis.setex(key, timer, value);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取Jedis 连接 【remember close Jedis】
     *
     * @return Jedis
     */
    public static Jedis getJedis() {
        return connectionFactory.fetchJedisConnector();
    }

    /**
     * 设置微信企业号 access token
     *
     * @param weixinQyAccessToken accessToken
     */
    public static void setWeixinQyAccessTokenCache(String weixinQyAccessToken) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            jedis.set(WEIXIN_QY_ACCESS_TOKEN_CACHE, weixinQyAccessToken);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取微信企业号 access token
     *
     * @return access token
     */
    public static String getWeixinQyAccessTokenCache() {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            return jedis.get(WEIXIN_QY_ACCESS_TOKEN_CACHE);
        } finally {
            jedis.close();
        }
    }

    /**
     * 设置微信 access token
     *
     * @param weixinAccessToken accessToken
     */
    public static void setWeixinAccessTokenCache(String weixinAccessToken) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            jedis.set(WEIXIN_ACCESS_TOKEN_CACHE, weixinAccessToken);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取微信 access token
     *
     * @return access token
     */
    public static String getWeixinAccessTokenCache() {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            return jedis.get(WEIXIN_ACCESS_TOKEN_CACHE);
        } finally {
            jedis.close();
        }
    }

    /**
     * 设置微信 user code
     *
     * @param drawUserValue
     */
    public static void setDrawUserCodeCache(String drawUserValue) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object authenticationObj = authentication.getPrincipal();
        UserVo user = null;
        if (!(authenticationObj instanceof String)) {
            user = (UserVo) authentication.getPrincipal();
        }
        if (null != user && StringUtils.isNotBlank(user.getUsername())) {
            try {
                jedis.setex(drawUserValue + "-" + DRAW_USER_SUFFIX_CACHE, DRAW_USER_TIMER, drawUserValue);
            } finally {
                jedis.close();
            }
        }
    }

    /**
     * 获取微信 user code
     *
     * @param drawUserId
     * @return user code
     */
    public static String getDrawUserCodeCache(String drawUserId) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        try {
            return jedis.get(drawUserId + "-" + DRAW_USER_SUFFIX_CACHE);
        } finally {
            jedis.close();
        }
    }

    /**
     * 设置微信 user code
     *
     * @param weixinUserCode
     */
    public static void setWeixinUserCodeCache(String weixinUserCode) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object authenticationObj = authentication.getPrincipal();
        String userId = "";
        if (!(authenticationObj instanceof String)) {
            User user = (User) authentication.getPrincipal();
            userId = null == user ? "" : user.getUsername();
        }
        // 暂时使用user.getUsername()。等待业务用户完善，替换userid
        try {
            jedis.set(userId + "-" + WEIXIN_USER_CODE_SUFFIX_CACHE, weixinUserCode);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取微信 user code
     *
     * @return user code
     */
    public static String getWeixinUserCodeCache() {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object authenticationObj = authentication.getPrincipal();
        String userId = "";
        if (!(authenticationObj instanceof String)) {
            User user = (User) authentication.getPrincipal();
            userId = null == user ? "" : user.getUsername();
        }
        // 暂时使用user.getUsername()。等待业务用户完善，替换userid
        try {
            return jedis.get(userId + "-" + WEIXIN_USER_CODE_SUFFIX_CACHE);
        } finally {
            jedis.close();
        }
    }

    /**
     * 设置微信当前菜单
     *
     * @param weixinThismenu 当前菜单
     */
    public static void setWeixinThismenuCache(String weixinThismenu) {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object authenticationObj = authentication.getPrincipal();
        String userId = "";
        if (!(authenticationObj instanceof String)) {
            User user = (User) authentication.getPrincipal();
            userId = null == user ? "" : user.getUsername();
        }
        // 暂时使用user.getUsername()。等待业务用户完善，替换userid
        try {
            jedis.set(userId + "-" + WEIXIN_THISMENU_SUFFIX_CACHE, weixinThismenu);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取微信 当前菜单
     *
     * @return 当前菜单
     */
    public static String getWeixinThismenuCache() {
        Jedis jedis = connectionFactory.fetchJedisConnector();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object authenticationObj = authentication.getPrincipal();
        String userId = "";
        if (!(authenticationObj instanceof String)) {
            User user = (User) authentication.getPrincipal();
            userId = null == user ? "" : user.getUsername();
        }
        // 暂时使用user.getUsername()。等待业务用户完善，替换userid
        try {
            return jedis.get(userId + "-" + WEIXIN_THISMENU_SUFFIX_CACHE);
        } finally {
            jedis.close();
        }
    }

    /**
     * 获取当前用户openid
     *
     * @return openid
     */
    public static String getUserWeixinOpenId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object authenticationObj = authentication.getPrincipal();
        String userId = "";
        if (!(authenticationObj instanceof String)) {
            UserVo user = (UserVo) authentication.getPrincipal();
            userId = null == user ? "" : user.getOpenId();
        }
        return userId;
    }

    /**
     * 加密银行卡号
     *
     * @param cardCode 银行卡号
     * @return 加密之后卡号
     */
    public static String encryptBankCard(String cardCode) {
        String bankSecureKey = getConstantPropertiesLoader().getProperty(App.BANK_SECURE_KEY);
        return Encodes.encryptAES(cardCode, bankSecureKey);
    }

    /**
     * 解密银行卡号
     *
     * @param cardCode 银行卡号
     * @return 解密之后卡号
     */
    public static String decryptBankCard(String cardCode) {
        String bankSecureKey = getConstantPropertiesLoader().getProperty(App.BANK_SECURE_KEY);
        if (StringUtils.isNotBlank(cardCode)) {
            return Encodes.decryptAES(cardCode, bankSecureKey);
        }
        return "";
    }

    /**
     * 解密APP端敏感信息
     *
     * @param content APP端加密敏感信息
     * @return APP端解密敏感信息
     */
    public static String decryptAppSensitiveInformation(String content) {
        String appSecureKey = getConstantPropertiesLoader().getProperty(App.BANK_SECURE_KEY);
        return Encodes.decryptAES(content, appSecureKey);
    }

    public static void main(String[] args) {
        String appSecureKey = getConstantPropertiesLoader().getProperty(App.BANK_SECURE_KEY);
        String encryptStr = Encodes.encryptAES("hello world", appSecureKey);
        System.out.println(encryptStr);

        System.out.println(Encodes.decryptAES(encryptStr, appSecureKey));

        System.out.println(getYeepayId());
    }

    /**
     * 获取易宝帐号id
     *
     * @return openid
     */
    public static String getYeepayId() {
        String yeepayId = getConstantPropertiesLoader().getProperty(App.YEEPAY_ID);
        return yeepayId;
    }

}
